package com.gnerv.pabu.basic.core.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;

public class JwtUtils {

    private static final Algorithm ALGORITHM = Algorithm.HMAC256("secret");
    private static final Long EXPIRE_TIME = 6000L;

    public static String create(String account){
        Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        String token = "";
        try {
            token = JWT.create()
                    .withClaim("account", account)
                    //到期时间
                    .withExpiresAt(date)
                    .withIssuer("gnerv")
                    .sign(ALGORITHM);
            return token;
        } catch (JWTCreationException exception){
            //Invalid Signing configuration / Couldn't convert Claims.
        }
        return token;
    }

    public static String verify(String token){
        try {
            JWTVerifier verifier = JWT.require(ALGORITHM)
                    .withIssuer("gnerv")
                    .build(); //Reusable verifier instance
            DecodedJWT jwt = verifier.verify(token);
            String account = jwt.getClaim("account").asString();
            return account;
        } catch (JWTVerificationException exception){
            //Invalid signature/claims
        }
        return "";
    }



}
